<?php
class SecurityPinField extends PasswordField {
    /**
     * Returns a "field holder" for this field - used by templates.
     * 
     * Forms are constructed by concatenating a number of these field holders.
     * The default field holder is a label and a form field inside a div.
     * @see FieldHolder.ss
     * 
     * @param array $properties key value pairs of template variables
     * @return string
     */
    public function FieldHolder($properties = array()) {
        if(Distributor::get_use_pin()){
            $obj = ($properties) ? $this->customise($properties) : $this;
    
            return $obj->renderWith($this->getFieldHolderTemplates());
        }
    }

    /**
     * Returns a restricted field holder used within things like FieldGroups.
     *
     * @param array $properties
     *
     * @return string
     */
    public function SmallFieldHolder($properties = array()) {
        if(Distributor::get_use_pin()){
            $obj = ($properties) ? $this->customise($properties) : $this;
    
            return $obj->renderWith($this->getSmallFieldHolderTemplates());
        }
    }
	
	function Type() {
		return 'securitypin text';
	}
    
    public function validate($validator) {
        if(Distributor::get_use_pin()){
            $member = $this->form->controller->CurrentMember();
            if(!$member || empty($this->value) || !$member->checkPin($this->value)->valid()) {
                $validator->validationError($this->name, _t('SecurityPinField.ERRORPINNOTMATCH', "Your current security pin does not match, please try again"));
                return false;
            }
			else{
				// Legacy migration.
				$migrate_legacy_hashes = Config::inst()->get('Distributor', 'migrate_legacy_hashes');
				if(isset($migrate_legacy_hashes[$member->PinEncryption])) {
					$member->Pin = $this->value;
					$member->PinEncryption = $migrate_legacy_hashes[$member->PinEncryption];
					$member->write();
				}
			}
        }

        return true;
    }
}
?>
